package com.shujia.wyh.mr.kqzl;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.output.MultipleOutputs;

import java.io.IOException;

public class KQZLReducer extends Reducer<Text, LongWritable, Text, LongWritable> {
    private MultipleOutputs<Text, LongWritable> multipleOutputs;

    @Override
    protected void setup(Context context) throws IOException, InterruptedException {
        multipleOutputs = new MultipleOutputs<Text, LongWritable>(context);
    }

    @Override
    protected void reduce(Text key, Iterable<LongWritable> values, Reducer<Text, LongWritable, Text, LongWritable>.Context context) throws IOException, InterruptedException {
        //<"日期:20180119-监测点编号:1001",[12,43,54,...]>
        long count = 0;
        long sum = 0;
        for (LongWritable value : values) {
            sum += value.get();
            count++;
        }

        long avg = sum / count;
//        context.write(key, new LongWritable(avg));

        String[] split = key.toString().split("\\$");
        // 自定义输出文件名
        multipleOutputs.write(new Text(split[0]), new LongWritable(avg), split[1]);
    }

    @Override
    protected void cleanup(Context context) throws IOException, InterruptedException {
        multipleOutputs.close();
    }
}
